package com.apes.hr.area.model;

import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.Name;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.hr.base.model.Employee;
import com.apes.scm.masterdata.frame.model.Branch;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Title: DeptArea
 * @Description: 门店区域配置
 * @author: ZhengZeXian
 * @create: 2021年8月19日10:29:12
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = DeptArea.CONST_TABLE_NAME)
public class DeptArea extends Model implements Comparable<DeptArea>{

    public static final String CONST_TABLE_NAME = "mas_dept_area";

    @Id
    @Column(name = "id", length = 64)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "门店区域配置", prefix = "ZG", padding = 2)
    @Comment("区域编码")
    private String id;

    @Name
    @Column(name = "name", nullable = false, length = 120)
    @Comment("区域名称")
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parents_id", referencedColumnName = "id")
    @Comment("上级区域")
    private DeptArea parents;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "employee_id", referencedColumnName = "id" )
    @Comment("区域负责人")
    private Employee employee;

    @Column(name = "levels", nullable = false, length = 120)
    @Comment("级别")
    private int levels;

    @Column(name = "is_last_stage", nullable = false)
    @Comment("末级标记")
    private boolean lastStage = false;

    @Column(name = "valid", nullable = false, columnDefinition = "number(1,0) default 1")
    @Comment("有效")
    private boolean valid = true;

    @OneToMany(mappedBy = "deptArea", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<DeptAreaItem> deptAreaItems = new ArrayList<>();

    public List<DeptAreaItem> getDeptAreaItems() {
        if (deptAreaItems == null) return null;
        for (DeptAreaItem item : deptAreaItems) {
            item.setDeptArea(this);
        }
        return deptAreaItems;
    }

    @Transient
    private String path;

    public String getPath() {
        String path = null;
        if (parents != null) path = parents.getPath();
        return path != null ? path + "/" + id : id;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof DeptArea)) return false;
        return (this.getId() == ((DeptArea) obj).getId());
    }

    @Override
    public int compareTo(DeptArea deptArea) {
        if(this.id == deptArea.id){
            return 1;
        }
        return 0;
    }
}

